package com.game.doudizhu.service;

import com.game.doudizhu.model.GameRoom;
import com.game.doudizhu.model.GameState;
import com.game.doudizhu.model.Player;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CacheService {

    private static final String ROOM_KEY_PREFIX = "game:room:";
    private static final String STATE_KEY_PREFIX = "game:state:";
    private static final String PLAYER_KEY_PREFIX = "game:player:";
    private static final String PLAYER_STATS_KEY_PREFIX = "game:player:stats:";
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 房间缓存操作
    public void cacheRoom(GameRoom room) {
        String key = ROOM_KEY_PREFIX + room.getId();
        redisTemplate.opsForValue().set(key, room, 30, TimeUnit.MINUTES);
    }

    public GameRoom getCachedRoom(Long roomId) {
        String key = ROOM_KEY_PREFIX + roomId;
        return (GameRoom) redisTemplate.opsForValue().get(key);
    }

    public void removeRoomCache(Long roomId) {
        String key = ROOM_KEY_PREFIX + roomId;
        redisTemplate.delete(key);
    }

    // 游戏状态缓存操作
    public void cacheGameState(Long roomId, GameState gameState) {
        String key = STATE_KEY_PREFIX + roomId;
        redisTemplate.opsForValue().set(key, gameState, 30, TimeUnit.MINUTES);
    }

    public GameState getCachedGameState(Long roomId) {
        String key = STATE_KEY_PREFIX + roomId;
        return (GameState) redisTemplate.opsForValue().get(key);
    }

    public void removeGameStateCache(Long roomId) {
        String key = STATE_KEY_PREFIX + roomId;
        redisTemplate.delete(key);
    }

    // 玩家在线状态缓存
    public void setPlayerOnline(Long playerId, Long roomId) {
        String key = PLAYER_KEY_PREFIX + playerId;
        redisTemplate.opsForValue().set(key, roomId, 30, TimeUnit.MINUTES);
    }

    public Long getPlayerRoom(Long playerId) {
        String key = PLAYER_KEY_PREFIX + playerId;
        return (Long) redisTemplate.opsForValue().get(key);
    }

    public void removePlayerCache(Long playerId) {
        String key = PLAYER_KEY_PREFIX + playerId;
        redisTemplate.delete(key);
    }

    // 更新玩家统计缓存
    public void updatePlayerStats(Player player) {
        String key = PLAYER_STATS_KEY_PREFIX + player.getId();
        redisTemplate.opsForValue().set(key, player, 30, TimeUnit.MINUTES);
    }

    // 获取玩家统计缓存
    public Player getPlayerStats(Long playerId) {
        String key = PLAYER_STATS_KEY_PREFIX + playerId;
        return (Player) redisTemplate.opsForValue().get(key);
    }

    // 删除玩家统计缓存
    public void removePlayerStats(Long playerId) {
        String key = PLAYER_STATS_KEY_PREFIX + playerId;
        redisTemplate.delete(key);
    }
}